package edu.yuhf.web.filter;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.DispatcherType;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@WebFilter(dispatcherTypes = {
				DispatcherType.REQUEST, 
				DispatcherType.FORWARD
		}
		, urlPatterns = { "/views/*" })
public class SessionCheckFilter implements Filter {

	public void destroy() {
	}

	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		HttpSession session=((HttpServletRequest)request).getSession();
		if(null!=session.getAttribute("name")) {
			chain.doFilter(request, response);
		}else {
			//((HttpServletResponse)response).sendRedirect(request.getServletContext().getContextPath()+"/");
			PrintWriter out=response.getWriter();
			out.print("<script>parent.window.location.href='"+request.getServletContext().getContextPath()+"/'"+"</script>");
			out.close();
		}
	}

	public void init(FilterConfig fConfig) throws ServletException {
	}

}
